/**
 * @Author: sxiaohao
 * @Description:
 * @File:  pay
 * @Version: 1.0.0
 * @Date: 2020/11/27 下午3:38
 */

package controller

import (
	"datum_textbook/config"
	"datum_textbook/utils"
	"datum_textbook/weChatPay"
	"github.com/gin-gonic/gin"
	"github.com/iGoogle-ink/gopay"
	"github.com/iGoogle-ink/gopay/wechat"
	"github.com/iGoogle-ink/gotil"
	"github.com/iGoogle-ink/gotil/xlog"
	"github.com/sirupsen/logrus"
	"net/http"
	"strconv"
)

func Order(ctx *gin.Context) {

	var totalFee = 0.00

	totalFee, _ = strconv.ParseFloat(ctx.PostForm("total_fee"), 32)

	number := gotil.GetRandomString(32)
	xlog.Debug("out_trade_no:", number)

	//初始化参数Map
	bm := make(gopay.BodyMap)
	//随机字符串，不长于32位。推荐随机数生成算法
	bm.Set("nonce_str", gotil.GetRandomString(32))
	//商品简单描述，该字段须严格按照规范传递
	bm.Set("body", config.GetString("weChatPay.body"))
	//商户系统内部的订单号,32个字符内、可包含字母
	bm.Set("out_trade_no", number)
	//订单总金额，单位为分
	bm.Set("total_fee", totalFee)
	//必须传正确的用户端IP,支持ipv4、ipv6格式，
	bm.Set("spbill_create_ip", ctx.ClientIP())
	//接收微信支付异步通知回调地址，通知url必须为直接可访问的url
	bm.Set("notify_url", config.GetString("weChatPay.notifyUrl"))
	//H5支付的交易类型为MWEB
	bm.Set("trade_type", wechat.TradeType_H5)
	//终端设备号(门店号或收银设备ID)，注意：PC网页或公众号内支付请传"WEB"
	bm.Set("device_info", "WEB")
	//sign := wechat.GetParamSign("wxdaa2ab9ef87b5497", "1368139502", "GFDS8j98rewnmgl45wHTt980jg543abc", body)
	//签名类型，目前支持HMAC-SHA256和MD5，默认为MD5
	bm.Set("sign_type", wechat.SignType_MD5)

	sceneInfo := make(map[string]map[string]string)
	h5Info := make(map[string]string)

	//场景类型
	h5Info["type"] = "Wap"
	//WAP网站URL地址
	h5Info["wap_url"] = config.GetString("weChatPay.wapUrl")
	//WAP 网站名
	h5Info["wap_name"] = config.GetString("weChatPay.wapName")
	//h5支付固定传"h5_info"
	sceneInfo["h5_info"] = h5Info
	bm.Set("scene_info", sceneInfo)

	//请求支付下单，成功后得到结果
	wxRsp, err := weChatPay.Client.UnifiedOrder(bm)
	if err != nil {
		utils.Response(ctx, http.StatusCreated, nil, "支付参数错误！")
		logrus.Info(err.Error())
		panic(err.Error())
	}

	utils.Response(ctx, http.StatusOK, map[string]interface{}{"MwebUrl": wxRsp.MwebUrl}, "success！")

	/*
		//获取H5支付需要的paySign
		timeStamp := strconv.FormatInt(time.Now().Unix(), 10)
		pac := "prepay_id=" + wxRsp.PrepayId
		paySign := wechat.GetH5PaySign(config.GetString("weChatPay.appId"), wxRsp.NonceStr, pac, wechat.SignType_MD5, timeStamp, config.GetString("weChatPay.apiKey"))
	*/

}

func Notify(ctx *gin.Context) {

	// ====支付异步通知参数解析和验签Sign====
	// 解析支付异步通知的参数
	//    req：*http.Request
	//    ctx.Request   是 gin 框架的获取 *http.Request
	//    返回参数 notifyReq：通知的参数
	//    返回参数 err：错误信息
	notifyReq, err := wechat.ParseNotifyToBodyMap(ctx.Request)
	if err != nil {
		panic(err.Error())
	}
	// 验签操作
	ok, verifyErr := wechat.VerifySign(config.GetString("weChatPay.apiKey"), wechat.SignType_MD5, notifyReq)

	if !ok {
		panic(verifyErr.Error())
	}

}

func OrderDetail(ctx *gin.Context) {

}

func OrderList(ctx *gin.Context) {

}
